package cn.muqingfeng.bbs.adapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.Html.TagHandler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import android.widget.Toast;
import cn.muqingfeng.api.RequestHelper;
import cn.muqingfeng.api.UriHelper;
import cn.muqingfeng.api.request.GsonRequest;
import cn.muqingfeng.api.to.ArticleDetailFloorsInfoTO;
import cn.muqingfeng.api.to.ArticleDetailThreadTO;
import cn.muqingfeng.api.to.BaseResponseTO;
import cn.muqingfeng.api.to.UserTO;
import cn.muqingfeng.bbs.R;
import cn.muqingfeng.bbs.ui.LoginActivity;
import cn.muqingfeng.bbs.ui.widget.SharePopup;
import cn.muqingfeng.util.BitmapBinder;
import cn.muqingfeng.util.FavCache;
import cn.muqingfeng.util.ViewHolder;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.Platform.ShareParams;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageContainer;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.android.volley.toolbox.NetworkImageView;

public class ArticleDetailAdapter extends BaseAdapter implements OnClickListener, Filterable {
	private static Drawable sDefaultDrawable = null;
	private static final int TYPE_FLOOR_HOST = 0;
	private static final int TYPE_FLOOR_OTHERS = 1;
	private List<ArticleDetailFloorsInfoTO> mPostList = new ArrayList<ArticleDetailFloorsInfoTO>();
	private List<ArticleDetailFloorsInfoTO> mAllPostList = new ArrayList<ArticleDetailFloorsInfoTO>();
	private ArticleDetailThreadTO mThread;
	private Activity mActivity;
	private Context mContext;
	private int mScreenWidth = 0;
	private int mScreenHeight = 0;
	private SharePopup mSharePopup;
	// 只看楼主
	private boolean only = false;
	private UserTO mUserTO;
	private final String mTid;
	private AlertDialog mNoLoginDialog;
	private List<String> mImageUrls = new ArrayList<String>();

	public ArticleDetailAdapter(Activity activity, String tid) {
		super();
		mActivity = activity;
		mTid = tid;
		mContext = activity.getApplicationContext();
		DisplayMetrics dm = new DisplayMetrics();
		mActivity.getWindowManager().getDefaultDisplay().getMetrics(dm);
		mScreenWidth = dm.widthPixels;
		mScreenHeight = dm.heightPixels;
		if (sDefaultDrawable == null) {
			sDefaultDrawable = new ColorDrawable(mActivity.getResources().getColor(
					R.color.default_image_color));
			int height = mActivity.getResources().getDimensionPixelSize(
					R.dimen.default_image_height);
			sDefaultDrawable.setBounds(0, 0, mScreenWidth, height);
		}
	}

	public void setArticleDetail(ArticleDetailThreadTO thread,
			List<ArticleDetailFloorsInfoTO> postlist) {
		this.mThread = thread;
		if (postlist != null && !postlist.isEmpty()) {
			mPostList.addAll(postlist);
			mAllPostList.addAll(postlist);
		}
	}

	public void setUserTO(UserTO mUserTO) {
		this.mUserTO = mUserTO;
	}

	@Override
	public int getItemViewType(int position) {
		return position == 0 ? TYPE_FLOOR_HOST : TYPE_FLOOR_OTHERS;
	}

	@Override
	public int getViewTypeCount() {
		return 2;
	}

	@Override
	public int getCount() {
		return mPostList.size();
	}

	@Override
	public Object getItem(int position) {
		return mPostList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		int type = getItemViewType(position);
		ArticleDetailFloorsInfoTO post = mPostList.get(position);
		switch (type) {
		case TYPE_FLOOR_HOST: {
			if (convertView == null) {
				convertView = View.inflate(mActivity, R.layout.article_detail_item_header, null);
			}
			NetworkImageView avatarView = ViewHolder.get(convertView, R.id.avatar);
			String authorid = mThread.getAuthorid();
			if (!TextUtils.isEmpty(authorid)) {
				String url = UriHelper.getAvatarUrl(authorid);
				BitmapBinder.bindNetImage(mActivity, avatarView, url, R.drawable.ic_default_avatar);
			} else {
				avatarView.setDefaultImageResId(R.drawable.ic_default_avatar);
				avatarView.setErrorImageResId(R.drawable.ic_default_avatar);
				avatarView.setImageResource(R.drawable.ic_default_avatar);
			}
			TextView nameView = ViewHolder.get(convertView, R.id.name);
			nameView.setText(mThread.getAuthor());
			TextView timeView = ViewHolder.get(convertView, R.id.time);
			timeView.setText(mThread.getDateline());
			TextView titleView = ViewHolder.get(convertView, R.id.title);
			titleView.setText(mThread.getTitle());
			TextView countView = ViewHolder.get(convertView, R.id.count);
			countView.setText(String.format("看 %d|回 %d", mThread.getViewCount(),
					mThread.getReplyCount()));
			TextView contentView = ViewHolder.get(convertView, R.id.content);
			loadContent(contentView, post.getContent());
			TextView onlyView = ViewHolder.get(convertView, R.id.only);
			onlyView.setText(only ? "查看所有" : "只看楼主");
			onlyView.setOnClickListener(this);
			Button favButton = ViewHolder.get(convertView, R.id.fav_opt);
			boolean isFaved = false;
			if (mUserTO != null) {
				isFaved = FavCache.isFaved(mContext, mUserTO.getUid(), mTid);
			}
			if (isFaved) {
				favButton.setOnClickListener(null);
				favButton.setText("已收藏");
			} else {
				favButton.setOnClickListener(this);
				favButton.setText("收藏该帖");
			}
			TextView share = ViewHolder.get(convertView, R.id.share);
			share.setOnClickListener(this);
		}
			break;
		case TYPE_FLOOR_OTHERS:
			if (convertView == null) {
				convertView = View.inflate(mActivity, R.layout.article_detail_item, null);
			}
			NetworkImageView avatarView = ViewHolder.get(convertView, R.id.avatar);
			String authorid = post.getAuthorId();
			if (!TextUtils.isEmpty(authorid)) {
				String url = UriHelper.getAvatarUrl(authorid);
				BitmapBinder.bindNetImage(mActivity, avatarView, url, R.drawable.ic_default_avatar);
			} else {
				avatarView.setDefaultImageResId(R.drawable.ic_default_avatar);
				avatarView.setErrorImageResId(R.drawable.ic_default_avatar);
				avatarView.setImageResource(R.drawable.ic_default_avatar);
			}
			TextView nameView = ViewHolder.get(convertView, R.id.name);
			nameView.setText(post.getAuthor());
			TextView timeView = ViewHolder.get(convertView, R.id.time);
			String time = post.getDateline();
			if(TextUtils.isEmpty(time)){
				timeView.setText(Html.fromHtml(time));
			}else{
				timeView.setText("");
			}
			TextView floorView = ViewHolder.get(convertView, R.id.floor);
			if (position == 1) {
				floorView.setText("沙发");
			} else {
				floorView.setText(position + "楼");
			}
			TextView contentView = ViewHolder.get(convertView, R.id.content);
			loadContent(contentView, post.getContent());
			break;
		}
		return convertView;
	}

	private void loadContent(TextView contentView, String content) {
		contentView.setText(Html.fromHtml(content, new ImageGetter() {

			@Override
			public Drawable getDrawable(String source) {
				if (!mImageUrls.contains(source)) {
					mImageUrls.add(source);
				}
				ImageLoader imageLoader = BitmapBinder.getImageLoader(mContext);
				ImageContainer imageContainer = imageLoader.get(source, new ImageListener() {

					@Override
					public void onErrorResponse(VolleyError error) {

					}

					@Override
					public void onResponse(ImageContainer response, boolean isImmediate) {
						if (response != null && response.getBitmap() != null) {
							notifyDataSetChanged();
						}
					}
				}, mScreenWidth, mScreenHeight);
				if (imageContainer.getBitmap() != null) {
					Drawable drawable = new BitmapDrawable(mContext.getResources(), imageContainer
							.getBitmap());
					int height = (int) (drawable.getIntrinsicHeight() * 1.0
							/ drawable.getIntrinsicWidth() * mScreenWidth);
					drawable.setBounds(0, 0, mScreenWidth, height);
					return drawable;
				}
				return sDefaultDrawable;
			}
		}, new TagHandler() {

			@Override
			public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {

			}
		}));
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.share:
			// hideSystemKeyBoard(mContext, view);
			// mSharePopup = new SharePopup(mActivity);
			// ViewGroup decor = (ViewGroup)
			// mActivity.getWindow().getDecorView();
			// mSharePopup.showAtLocation(decor, Gravity.BOTTOM, 0, 0);
			share();
			break;
		case R.id.fav_opt:
			if (mUserTO == null) {
				showNOLoginDialog();
			} else {
				addFav(view);
			}
			break;
		case R.id.only:
			only = !only;
			getFilter().filter("");
			break;
		default:
			break;
		}
	}

	private void share() {
		ShareSDK.initSDK(mContext);
		ShareParams sp = new ShareParams();
		sp.setShareType(Wechat.SHARE_WEBPAGE);
		sp.setUrl(UriHelper.getWebDetailUrl(mTid));
		sp.setText(mThread.getTitle());
		sp.setTitle(mThread.getTitle());
		if (!mImageUrls.isEmpty()) {
			sp.setImageUrl(mImageUrls.get(0));
		}
		Platform weichat = ShareSDK.getPlatform(WechatMoments.NAME);
		weichat.setPlatformActionListener(new PlatformActionListener() {

			@Override
			public void onError(Platform arg0, int arg1, Throwable arg2) {

			}

			@Override
			public void onComplete(Platform arg0, int arg1, HashMap<String, Object> arg2) {
				Toast.makeText(mContext, "分享成功", Toast.LENGTH_SHORT).show();
			}

			@Override
			public void onCancel(Platform arg0, int arg1) {

			}
		}); // 设置分享事件回调
		// 执行图文分享
		weichat.share(sp);
	}

	public void hideSystemKeyBoard(Context mcontext, View v) {
		InputMethodManager imm = (InputMethodManager) (mContext
				.getSystemService(Context.INPUT_METHOD_SERVICE));
		imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
	}

	private synchronized void showNOLoginDialog() {
		if (mNoLoginDialog != null && mNoLoginDialog.isShowing()) {
			return;
		}
		AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
		builder.setTitle("提示");
		builder.setMessage("您还未登录，是否立即登录？");
		builder.setNegativeButton("否", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

			}
		});
		builder.setPositiveButton("是", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				Intent intent = new Intent(mActivity, LoginActivity.class);
				mActivity.startActivity(intent);
			}
		});
		mNoLoginDialog = builder.create();
		mNoLoginDialog.show();
	}

	@Override
	public Filter getFilter() {
		return new Filter() {

			@Override
			protected void publishResults(CharSequence constraint, FilterResults results) {
				mPostList = (List<ArticleDetailFloorsInfoTO>) results.values;
				notifyDataSetChanged();
			}

			@Override
			protected FilterResults performFiltering(CharSequence constraint) {
				FilterResults results = new FilterResults();
				if (only) {
					ArticleDetailFloorsInfoTO post = mAllPostList.get(0);
					ArrayList<ArticleDetailFloorsInfoTO> list = new ArrayList<ArticleDetailFloorsInfoTO>();
					for (ArticleDetailFloorsInfoTO to : mAllPostList) {
						if (post.getAuthorId().equals(to.getAuthorId())) {
							list.add(to);
						}
					}
					results.count = list.size();
					results.values = list;
				} else {
					results.count = mAllPostList.size();
					results.values = mAllPostList;
				}
				return results;
			}
		};
	}

	public void addFav(final View view) {
		view.setClickable(false);
		String requestUrl = UriHelper.getAddFavArticleUrl();
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("id", mTid);
		GsonRequest<BaseResponseTO> request = new GsonRequest<BaseResponseTO>(Method.POST,
				requestUrl, new Listener<BaseResponseTO>() {

					@Override
					public void onResponse(BaseResponseTO response) {
						view.setClickable(true);
						if (response == null) {
							Toast.makeText(mContext, "收藏失败,请重试!", Toast.LENGTH_SHORT).show();
						} else {
							if (response.isSuccess()) {
								Toast.makeText(mContext, "收藏成功", Toast.LENGTH_SHORT).show();
								FavCache.addFav(mContext, mUserTO.getUid(), mTid);
								notifyDataSetChanged();
							} else {
								String msg = response.getMessage();
								msg = TextUtils.isEmpty(msg) ? "收藏失败,请重试!" : msg;
								Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
							}
						}
					}
				}, new ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						view.setClickable(true);
						Toast.makeText(mContext, "收藏失败,请重试!", Toast.LENGTH_SHORT).show();
					}
				}, params, BaseResponseTO.class);
		request.setNeedLogin(true);
		RequestHelper.startRequest(mContext, request);
	}
}
